<?php

/**
 * 商品接口
 */
class ProductController extends ControllerBase {

    private $product_columns = 'product_id, product_name, sell_price, catimg AS product_image, product_subname AS product_breif, product_unit, product_instocks';

    /**
     * 获取商品信息 [GET]
     * 接口请求地址：/product/get_info/
     * @param int $product_id 商品Id
     * @example 商品图片数据：[图片url, 图片url...]
     * @example 返回结果：{"retcode":0,"retmsg":{"product_id":999,"product_name":"商品名称","sell_price":999.99,"product_image":"商品首图地址","images":[商品图片列表]"product_unit":"商品单位","product_instocks":999,"product_storage":"商品存储环境","product_origin":"商品产地","product_breif":"商品简介","product_desc":"商品详细描述"}}
     * @example 样品JSON : <a href="http://182.92.164.200:82/json_product_info.json" target="_blank">http://182.92.164.200:82/json_product_info.json</a>
     */
    public function get_infoAction() {
        global $config;
        $product_id = InputUtil::digitDefault($this->request->get('product_id'), 0);
        if ($product_id > 0) {
            $product = Product::findFirst([
                "product_id = $product_id AND is_delete = 0",
                "columns" => "product_id, product_name, sell_price, catimg AS product_image, product_unit, product_instocks, product_storage, product_origin, product_subname AS product_breif, product_desc"
            ]);
            if ($product) {
                $product->product_image = $config->base->domainbase . 'uploads/product_hpic/' . $product->product_image;
                // 获取商品图片列表
                $images = ProductImages::find("product_id = $product_id");
                $imagesnew = [];
                if ($images) {
                    $images = $images->toArray();
                    foreach ($images as $img) {
                        $imagesnew[] = $config->base->domainbase . 'uploads/product_hpic/' . $img['image_path'];
                    }
                }
                unset($images);
                $product->images = $imagesnew;
                $this->echoJson([
                    'retcode' => 0,
                    'retmsg' => Util::digitFix($product)
                ], false);
            } else {
                $this->echoErrcode(ErrorCode::$ERR_PRODUCT_NOTEXT);
            }
        } else {
            $this->echoErrcode(ErrorCode::$ERR_PARAMS_ERROR);
        }
    }

    /**
     * 获取商品列表 [POST]
     * 接口请求地址：/product/get_list/
     * @param int $pageno 第几页 默认0
     * @param int $pagesize 每页显示的数量 默认20
     * @param int $catid 商品分类Id 搜索时可传0
     * @param string $searchkey 搜索关键字
     * @example 返回结果：{"retcode":0,"retmsg":[
     *  {"product_id":999,"product_name":"商品名称","sell_price":999.99,"product_image":"商品图片地址","product_unit":"商品单位","product_breif":"商品简介","product_instocks":999},
     *  {"product_id":999,"product_name":"商品名称","sell_price":999.99,"product_image":"商品图片地址","product_unit":"商品单位","product_breif":"商品简介","product_instocks":999},
     *  {"product_id":999,"product_name":"商品名称","sell_price":999.99,"product_image":"商品图片地址","product_unit":"商品单位","product_breif":"商品简介","product_instocks":999},=
     * ]}
     */
    public function get_listAction() {
        global $config;
        $pageno = InputUtil::digitDefault($this->request->getPost('pageno'), 0);
        $pagesize = InputUtil::digitDefault($this->request->getPost('pagesize'), 20);
        $catid = InputUtil::digitDefault($this->request->getPost('catid'), 0);
        $searchkey = $this->request->getPost('searchkey');
        $sqlBulider = $this->modelsManager->createBuilder();
        $sqlBulider->where("is_delete = 0");
        if (!empty($searchkey)) {
            // 搜索字段
            $sqlBulider->andWhere("product_name LIKE '%$searchkey%'");
        }
        if ($catid > 0) {
            $sqlBulider->andWhere("product_cat = $catid");
        }
        $list = $sqlBulider
            ->columns($this->product_columns)
            ->from('Product')
            ->limit($pagesize, $pageno * $pagesize)
            ->orderBy("product_id DESC")
            ->getQuery()
            ->execute();
        $ret = $list->toArray();
        foreach ($ret as &$r) {
            $r['product_image'] = $config->base->domainbase . 'uploads/product_hpic/' . $r['product_image'];
        }
        $this->echoMsg(0, Util::digitFix($ret));
    }

    /**
     * 获取商品评价 [GET]
     * 接口请求地址：/product/get_comments/
     * @param int $product_id 商品Id
     * @example 返回结果：{"retcode":0,"retmsg":[{uid: 用户Id,centent: 评价内容,mtime: 创建时间,username: 用户名,userhead: 用户头像}]}
     */
    public function get_commentsAction() {
        $product_id = InputUtil::digitDefault($this->request->get('product_id'), 0);
        if ($product_id) {
            $ext = Product::findFirst("product_id = $product_id");
            if ($ext) {
                $list = OrderComment::find([
                    "product_id = $product_id",
                    'columns' => 'uid, content, mtime',
                    'order' => 'mtime DESC'
                ])->toArray();
                foreach ($list as &$lst) {
                    $user = User::findFirst("client_id = {$lst['uid']}");
                    $lst['username'] = $user->client_name;
                    $lst['userhead'] = $user->client_head;
                }
                $this->echoMsg(0, Util::digitFix($list));
            } else {
                $this->echoErrcode(ErrorCode::$ERR_PRODUCT_NOTEXT_COMM);
            }
        } else {
            $this->echoErrcode(ErrorCode::$ERR_PARAMS_ERROR);
        }
    }

    /**
     * 获取首页顶部滚动图 [GET]
     * 接口请求地址：/product/get_banners/
     * @example 样品JSON : <a href="http://182.92.164.200:82/json_get_banners.json" target="_blank">http://182.92.164.200:82/json_get_banners.json</a>
     * @example 返回结果：{"retcode":0,"retmsg":["image": 图片地址(string), "product_id": 对应产品Id(int), "sort": 排序(int)]}
     */
    public function get_bannersAction() {
        global $config;
        $banners = Banners::find([
            "id > 0",
            'columns' => 'banner_image AS image, relid AS product_id, sort',
            'order' => 'sort DESC'
        ]);
        if ($banners) {
            $banners = $banners->toArray();
            foreach ($banners as &$banner) {
                $banner['sort'] = intval($banner['sort']);
                $banner['product_id'] = intval($banner['product_id']);
                $banner['image'] = $config->base->domainbase . 'uploads/banner/' . $banner['image'];
            }
            $this->echoMsg(0, $banners);
        } else {
            $this->echoMsg(0, []);
        }
    }

    /**
     * 获取首页推荐商品列表 [GET]
     * 接口请求地址：/product/get_recomment_products/
     * @param int $pageno 第几页 默认0
     * @param int $pagesize 每页显示的数量 默认20
     * @example 样品JSON : <a href="http://182.92.164.200:82/json_get_reomment_products.json" target="_blank">http://182.92.164.200:82/json_get_reomment_products.json</a>
     * @example 返回结果：{"retcode":0,"retmsg":获取商品信息列表中的数据类型}
     */
    public function get_recomment_productsAction() {
        global $config;
        $pageno = InputUtil::digitDefault($this->request->get('pageno'), 0);
        $pagesize = InputUtil::digitDefault($this->request->get('pagesize'), 20);
        // 获取列表
        $sqlBulider = $this->modelsManager->createBuilder();
        $sqlBulider->where("is_delete = 0");
        $list = $sqlBulider
            ->columns($this->product_columns)
            ->from('Product')
            ->where("product_prom = 1")
            ->limit($pagesize, $pageno * $pagesize)
            ->orderBy("product_id DESC")
            ->getQuery()
            ->execute();
        if ($list->count() > 0) {
            $ret = $list->toArray();
            foreach ($ret as &$r) {
                $r['product_id'] = intval($r['product_id']);
                $r['sell_price'] = floatval($r['sell_price']);
                $r['product_instocks'] = intval($r['product_instocks']);
                $r['product_image'] = $config->base->domainbase . 'uploads/product_hpic/' . $r['product_image'];
            }
        } else {
            $ret = [];
        }
        $this->echoMsg(0, $ret);
    }

    /**
     * 获取热门搜索关键字列表 [GET]
     * 接口请求地址：/product/get_hot_search_keyword/
     * @example 返回结果：{"retcode":0,"retmsg":["牛排","牛排","牛排","牛排","牛排"]}
     * @example 返回结果数量不定
     */
    public function get_hot_search_keywordAction() {
        $hot_search_keywords = [];
        $hot_search_keyword = Settings::get('hot_search_keyword');
        if (!empty($hot_search_keyword)) {
            $hot_search_keyword = str_replace('，', ',', $hot_search_keyword);
            $hot_search_keywords = explode(',', $hot_search_keyword);
            foreach ($hot_search_keywords as $index => &$kw) {
                if (empty($kw)) {
                    unset($hot_search_keywords[$index]);
                } else {
                    $kw = trim($kw);
                }
            }
        }
        $this->echoMsg(0, $hot_search_keywords);
    }

}
